package gentle.service.impl;

import gentle.base.SqlMapper;
import gentle.entity.*;
import gentle.service.IConsultantDetailsService;
import gentle.service.MemberProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;


@Service
@Transactional
public class ConsultantDetailsServiceImpl implements IConsultantDetailsService {

    @Autowired
    private SqlMapper sqlMapper;

    @Autowired
    private MemberProductService memberProductService;

    public ScoreDealInfo orderOperation(String reservationsId) {
        String sql1="select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from score_deal " +
                " where reservations_id='"+reservationsId+"'";
        ScoreDealInfo scoreDealInfo=sqlMapper.selectOne(sql1,ScoreDealInfo.class);
        return scoreDealInfo;
    }

    public VipLevelInfo getVipLevel(String reservationsId,String abbreviation) {
        VipLevelInfo vipLevelInfo = memberProductService.getVipLevel(reservationsId,abbreviation);
        if(vipLevelInfo==null){
            vipLevelInfo.setVipLevelName("入门会员");
            vipLevelInfo.setDiscountDiscount(1);
        }else{
            vipLevelInfo.setVipLevelName(vipLevelInfo.getVipLevelName());
            vipLevelInfo.setDiscountDiscount(vipLevelInfo.getDiscountDiscount());
        }
        return vipLevelInfo;
    }

    public String getMoneyBalance (String reservationsId){
        String sql2 = "select if(sum(a.actual_account_balance) is null,0,sum(a.actual_account_balance)) as moneyBalance from reservemoney_deal a " +
                " where a.reservations_id='"+reservationsId+ "' limit 1";
        MembersUser membersUser = sqlMapper.selectOne(sql2, MembersUser.class);
        return membersUser.getMoneyBalance();
    }

    //获取抵扣方式
    public String getObtainDeductionMethod(){
        String checkoutSql = "select id,checkout_method from checkout_method_info where type in ('1','2')";
        List<CheckoutMethodInfo> checkoutMethodList = sqlMapper.selectList(checkoutSql, CheckoutMethodInfo.class);
        String checkoutMethodHtml = "";
        for (int i = 0; i < checkoutMethodList.size(); i++) {
            checkoutMethodHtml += "<option value='" + checkoutMethodList.get(i).getId() + "'>" + checkoutMethodList.get(i).getCheckoutMethod() + "</option>";
        }
        return checkoutMethodHtml;
    }

    //开单记录
    public List<PayServicedInfo> orderDealListTc(String reservationsId,String abbreviation,String areaAbbreviation){
        String ptable=areaAbbreviation+"pay_service_info";
        String abbreviationSql = "select abbreviation from distinction_customer_status where reservations_id = '" + reservationsId + "' and status=1 ";
        List<String> abbreviationList = sqlMapper.selectList(abbreviationSql, String.class);
        String dealTables = "";
        String dealTables2 = "";
        for (int i = 0; i < abbreviationList.size(); i++) {
            String head = abbreviationList.get(i);
            String s = "select id,area_abbreviation from dept where abbreviation='" + abbreviationList.get(i) + "'";
            Dept dept = sqlMapper.selectOne(s, Dept.class);
            if (i == abbreviationList.size() - 1) {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' ";
                dealTables2 += "select a.*,t2.id AS payServiceId, t2.department AS department,t2.first_level_project AS firstLevelProject," +
                        " t2.pay_service_name AS payServiceName, t2.pay_service_price_one AS payServicePriceOne," +
                        " t2.pay_service_price_two AS payServicePriceTwo,t2.unit as unit," +
                        " t3.customer_name AS customerName,t3.medical_record_number AS medicalRecordNumber,t3.customer_phone AS customerPhone," +
                        " t3.customer_age AS customerAge," +
                        " (CASE t3.customer_sex WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '未知' END " +
                        " ) as sex " +
                        " from " + head + "deal_info a left join " + dept.getAreaAbbreviation() + "pay_service_info t2 on a.pay_service_id=t2.id " +
                        " left join " + head + "customer_info t3 on a.customer_id=t3.id " +
                        " where a.reservations_id='" + reservationsId + "'";
            } else {
                dealTables += "select * from " + head + "deal_info where reservations_id='" + reservationsId + "' union ";
                dealTables2 += "select a.*,t2.id AS payServiceId, t2.department AS department,t2.first_level_project AS firstLevelProject," +
                        " t2.pay_service_name AS payServiceName, t2.pay_service_price_one AS payServicePriceOne," +
                        " t2.pay_service_price_two AS payServicePriceTwo,t2.unit as unit," +
                        " t3.customer_name AS customerName,t3.medical_record_number AS medicalRecordNumber,t3.customer_phone AS customerPhone," +
                        " t3.customer_age AS customerAge," +
                        " (CASE t3.customer_sex WHEN 1 THEN '男' WHEN 2 THEN '女' ELSE '未知' END " +
                        " ) as sex " +
                        " from " + head + "deal_info a left join " + dept.getAreaAbbreviation() + "pay_service_info t2 on a.pay_service_id=t2.id " +
                        " left join " + head + "customer_info t3 on a.customer_id=t3.id " +
                        " where a.reservations_id='" + reservationsId + "' union ";
            }
        }
        //通过预约ID  获得开单记录
        String sql = "select t1.id as id,t1.customer_id as customerId,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus,t1.nurse  as nurse, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.get_time,19) as operationTime,t1.remarks as remarks,t1.doctor as doctor,t1.primary_amount as primaryAmount," +
                " t1.folding_pay as foldingPay,t1.pay_service as payService,t1.whole_discount as wholeDiscount,t1.discount_hide as discountHide," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject,t1.arrears as arrears," +
                "t2.pay_service_name as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "t1.order_discount as orderDiscount,t1.deduction_type as deductionType," +
                "t1.deduction_amount as deductionAmount,t1.deposit_amount as depositAmount,t1.deduction_typeName as deductionTypeName,t1.is_do as isDo ,t1.orthodontic_number as orthodonticNumber,t1.operation_time as operationTime " +
                " from (" + dealTables + ") t1 left join " + ptable+ " t2 on t1.pay_service_id=t2.id " +
                " where t1.reservations_id='" + reservationsId + "' and pay_service_id is not null group by operationTime order by operationTime desc";
        List<PayServicedInfo> payServiceInfoListS = sqlMapper.selectList(sql, PayServicedInfo.class);
        String getTime = "";
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;
        Double totleServiceActualPay = 0.00;
        Double accountArrears = 0.00;
        for (PayServicedInfo info : payServiceInfoListS) {
            if (info != null) {
                if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                    if (info.getPayServiceNum() != null) {
                        totleReceivable += (info.getPayServicePriceTwo()) * (info.getPayServiceNum());
                    }
                    if (info.getFoldingPay() != null) {
                        totleFoldingPay += info.getFoldingPay();
                    }
                    if (info.getServiceActualPay() != null) {
                        totleServiceActualPay += info.getServiceActualPay();
                    }
                    if (info.getArrears() != null) {
                        accountArrears += info.getArrears();
                    }
                    info.setTotleReceivable(totleReceivable);
                    info.setTotleFoldingPay(totleFoldingPay);
                    info.setTotleServiceActualPay(totleServiceActualPay);
                    info.setAccountArrears(accountArrears);
                }
                if (info.getOperationTime() != "" && info.getOperationTime() != null) {
                    info.setOperationTimeOne(info.getOperationTime().substring(0, 10));
                    info.setOperationTimeTwo(info.getOperationTime().substring(11, info.getOperationTime().length()));
                }
                getTime = info.getGetTime();
            }
            String sql3 = "SELECT SUM(service_actual_pay) as serviceActualPay,sum(deposit_amount) as depositAmount," +
                    " sum(arrears) as  accountArrears, " +
                    " t1.id AS id,t1.customer_id AS customerId,t1.reservations_id AS reservationsId,LEFT(t1.get_time,19) AS getTime,t1.outpatient_name AS outpatientName, " +
                    " t1.deal_status AS dealStatus, t1.tc_name AS tcName,t1.pay_service_num AS payServiceNum,t1.pay_service_numold AS payServiceNumOld," +
                    " t1.whole_discount as wholeDiscount,t1.discount_hide as discountHide," +
                    " (case when t1.is_do=3 then '还欠款' when t1.is_do=4 then '退款' when t1.is_do=5 then '消费' when t1.is_do=6 then '作废' end ) isDoName,t1.primary_amount as primaryAmount," +
                    " LEFT(t1.operation_time,19) AS operationTime,t1.remarks AS remarks, t1.folding_pay AS foldingPay,t1.doctor AS doctor,t1.nurse AS nurse," +
                    " t1.left_up AS leftUp,t1.left_down AS leftDown,t1.right_up AS rightUp,t1.right_down AS rightDown,t1.pay_service AS payService,t1.payServiceId," +
                    " t1.department,t1.firstLevelProject,t1.payServiceName,t1.payServicePriceOne, " +
                    " t1.payServicePriceTwo,t1.unit,t1.customerName," +
                    " t1.medicalRecordNumber,t1.customerPhone,t1.customerAge, " +
                    " t1.sex,t1.tc_name AS fieldTc,t1.order_discount as orderDiscount,t1.deduction_type as deductionType,t1.id2," +
                    " t1.deduction_amount as deductionAmount,t1.deduction_typeName as deductionTypeName,t1.check_status AS checkStatus  " +
                    " from (" + dealTables2 + ") t1 " +
                    " where t1.get_time='" + info.getOperationTime() + "' and t1.reservations_id='" + reservationsId + "' " +
                    " and (t1.deal_status in ('已结账','待审核','审核未通过') or (t1.deal_status in ('已开单','待审核','审核未通过')))" +
                    " GROUP BY t1.id2,t1.get_time  order by t1.get_time desc ";
            List<PayServicedInfo> openBillList = sqlMapper.selectList(sql3, PayServicedInfo.class);
            info.setDealList(openBillList);
        }
        return payServiceInfoListS;
    }

    public Double getJfbalance(String reservationsId, String proportional){
        String jfbalancesql = "select if(sum(score_balance) is null,0,sum(score_balance)) as scoreBalance from return_cash_info where reservations_id='" + reservationsId + "'";
        ScoreDealInfo scoreDealInfo = sqlMapper.selectOne(jfbalancesql, ScoreDealInfo.class);
        BigDecimal b1 = new BigDecimal(Double.parseDouble(proportional));
        BigDecimal b2 = new BigDecimal(Double.parseDouble(scoreDealInfo.getScoreBalance()));
        Double khjfbalance = b1.multiply(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return khjfbalance;
    }

    public List<NurseInfo> getNurseList(String abbreviation){
        String sql = " select a.id as id,a.name as nurse from user a left join dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                " where a.status='1' and (b.abbreviation='" + abbreviation+ "' and c.name in ('护士','护士长','前台人员') and a.`status`='1')";
        List<NurseInfo> list = sqlMapper.selectList(sql, NurseInfo.class);
        return list;
    }

    public List<TcInfo> getTcList(String abbreviation){
        String sql = " select a.id as id,a.account as tcName from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                " where b.abbreviation='" + abbreviation+ "' and c.name like CONCAT('%','tc','%') ";
        List<TcInfo> list = sqlMapper.selectList(sql, TcInfo.class);
        return list;
    }

    public List<SfInfo> getSfList(String userName) {
        String sql = "select * from tc_follow_template where user='" + userName+ "'";
        List<SfInfo> list = sqlMapper.selectList(sql, SfInfo.class);
        return list;
    }

    public List<JgInfo> getJgList(String userName) {
        String sql = "select * from tc_follow_results_template where user='" + userName+ "'";
        List<JgInfo> list = sqlMapper.selectList(sql, JgInfo.class);
        return list;
    }

    public List<DoctorInfo> getDoctorList(String abbreviation){
        String sql = " select a.id as id,a.account as doctor from user a left join  dept b on a.deptid like CONCAT('%',b.id,',','%') left join role c on find_in_set(c.id,a.roleid) > 0 " +
                " where b.abbreviation='" +abbreviation+ "' and (c.name='医生' or c.name='洁牙师') and a.status='1';";
        List<DoctorInfo> list = sqlMapper.selectList(sql, DoctorInfo.class);
        return list;
    }

    public List<DepartmentInfo> getDepartmentList(String areaAbbreviation){
        String ptable=areaAbbreviation+"pay_service_grade_info";
        String sql = "select a.department as department from " +ptable+ " a where a.is_upper=1 group by a.department order by a.id;";
        List<DepartmentInfo> list = sqlMapper.selectList(sql, DepartmentInfo.class);
        return list;
    }

    public ConsultantInfo diagnoseTc(String reservationsId) {
        //tc看诊记录
        String sql1 = "select id as id, customer_id as customerId,left(diagnosis_time,19) as diagnosisTime, " +
                "left(diagnosis_time,11) as diagnosisTimeOne,substring(diagnosis_time,12,10) as diagnosisTimeTwo," +
                "replace(diagnosis_content,'& lt;br/& gt;','</br>') as diagnosisContent,reservations_id as reservationsId,tc_name as tcName " +
                "from tc_diagnosis_info where reservations_id='" + reservationsId + "' order by diagnosis_time asc";
        List<ConsultantInfo> consultantInfoList = sqlMapper.selectList(sql1, ConsultantInfo.class);
        if (consultantInfoList.size() > 0) {
            for (ConsultantInfo info1 : consultantInfoList) {
                if (info1.getDiagnosisTime() != "" && info1.getDiagnosisTime() != null) {
                    info1.setDiagnosisTimeOne(info1.getDiagnosisTime().substring(0, 10));
                    info1.setDiagnosisTimeTwo(info1.getDiagnosisTime().substring(11, info1.getDiagnosisTime().length()));
                }
            }
        }
        //tc回访记录
        String sql2 = "select r.*," +
                "(case r.revisit_status " +
                " WHEN 1 then '待计划' " +
                " WHEN 1 then '回访完成' " +
                " WHEN 1 then '回访未完成' " +
                " WHEN 1 then '回访取消'" +
                " else '' end) as revisitStatusName" +
                " from return_tc_visit_info r " +
                " where r.reservations_id ='" +reservationsId+ "' order by revisit_time desc";
        List<TcRevisitsInfo> tcRevisitInfoList = sqlMapper.selectList(sql2, TcRevisitsInfo.class);
        for (TcRevisitsInfo info1 : tcRevisitInfoList) {
            if (info1.getRevisitTime() != "" && info1.getRevisitTime() != null) {
                info1.setRevisitTime(info1.getRevisitTime().substring(0, 11));
            }
        }
        //市场回访记录
        String sql3 = "select id,replace(huifang ,',<b>','</br><b>') as huifang from reservations_info where id ='" +reservationsId+ "' ";
        ReservationsInfo reservationInfo = sqlMapper.selectOne(sql3, ReservationsInfo.class);
        ConsultantInfo info=new ConsultantInfo();
        info.setConsultantInfoList(consultantInfoList);
        info.setTcRevisitsInfoList(tcRevisitInfoList);
        info.setReservationsInfo(reservationInfo);
        return info;
    }

}